package com.roc.template.websocket;

import com.alibaba.fastjson.JSON;
import com.roc.template.base.Result;
import com.roc.template.mongo.model.RemoteUser;
import com.roc.template.mongo.service.RemoteUserService;
import com.roc.template.cloud.util.HttpClientUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName SocketController
 * @Description: TODO
 * @Author Administrator
 * @Date 2020/7/17 14 40
 * @Version V1.0
 **/

@Api(description = "websocket连接")
@RestController
@RequestMapping("/remote")
public class SocketController {

    @Resource
    private RemoteUserService remoteUserService;

    protected Logger logger = LoggerFactory.getLogger(SocketController.class);

    @ApiOperation("发起远程控制")
    @PostMapping("/remoteCall.json")
    public Result getUser(@RequestBody SocketVo socketVo) {
        if(socketVo.getToWbUserId()==null || socketVo.getoId() ==null) {
            return new Result(true, "oId或toWbUserId参数不能为空","-1", "");
        }

        RemoteUser remoteUser = new RemoteUser();
        remoteUser.setCreatorWbUserId(socketVo.getoId());
        remoteUser.setToWbUserId(socketVo.getToWbUserId());
        remoteUser.setCreateRefreshTime(new Date());
        remoteUser.setToRefreshTime(new Date());
        remoteUserService.insert(remoteUser);
        logger.info("申请远程"+ JSON.toJSONString(socketVo));

        SocketBean socketBean = new SocketBean();
        socketBean.setEvent(socketVo.getRemoteStatus());
        socketBean.setCreatorWbUserId(socketVo.getoId());
        socketBean.setToWbUserId(socketVo.getToWbUserId());

        Map<String, Object> param = new HashMap<>();
        param.put("fromSystem", "remote");
        param.put("userIds", new String[]{socketVo.getToWbUserId()});
        param.put("msg", socketBean);
        logger.info("参数"+ JSON.toJSONString(param));
        String post = HttpClientUtils.post("https://dev.kdweibo.cn/xtinterface/extSys/sendNotify", JSON.toJSONString(param));
        logger.info("申请远程"+ post);
        return new Result(true, "","", "");

    }

    @ApiOperation("加入远程")
    @PostMapping("/remoteJoin.json")
    public Result remoteJoin(@RequestBody SocketVo socketVo, HttpServletRequest request) {
        if(socketVo.getoId() ==null || socketVo.getCreatorWbUserId() ==null) {
            return new Result(false, "oId或createWbUserId不能为空！","-1", "");
        }

        logger.info("加入远程"+ JSON.toJSONString(socketVo));

        SocketBean socketBean = new SocketBean();
        socketBean.setEvent(2);
        socketBean.setCreatorWbUserId(socketVo.getCreatorWbUserId());
        socketBean.setRemotePstrAddress(socketVo.getRemotePstrAddress());
        socketBean.setRemotePstrSession(socketVo.getRemotePstrSession());

        Map<String, Object> param = new HashMap<>();
        param.put("fromSystem", "remote");
        param.put("userIds", new String[]{socketVo.getCreatorWbUserId()});
        param.put("msg", socketBean);

        String post = HttpClientUtils.post("https://dev.kdweibo.cn/xtinterface/extSys/sendNotify", JSON.toJSONString(param));
        logger.info("加入远程"+ post);
        return new Result(true, "","", "");

    }

    @ApiOperation("远程关闭")
    @PostMapping("/remoteShut.json")
    public Result remoteShut(@RequestBody SocketVo socketVo) {

        if(socketVo.getoId() ==null) {
            return new Result(false, "oId不能为空","-1", "");
        }

        logger.info("远程关闭"+ JSON.toJSONString(socketVo));
        SocketBean socketBean = new SocketBean();
        socketBean.setEvent(3);
//
        RemoteUser remoteUser = remoteUserService.getByToUser(socketVo.getoId());
        if(remoteUser ==null) {
            remoteUser = remoteUserService.getByCreateUser(socketVo.getoId());
        }

        if(remoteUser==null) return new Result(false, "连接已关闭","-1", "");

        Map<String, Object> param = new HashMap<>();
        param.put("fromSystem", "remote");
        param.put("userIds", new String[]{remoteUser.getCreatorWbUserId(), remoteUser.getToWbUserId()});
        param.put("msg", socketBean);

        remoteUserService.delete(remoteUser.getId());

        String post = HttpClientUtils.post("https://dev.kdweibo.cn/xtinterface/extSys/sendNotify", JSON.toJSONString(param));
        logger.info("远程关闭"+ post);
        return new Result(true, "","", "");

    }

    @ApiOperation("远程拒绝")
    @PostMapping("/remoteRefuse.json")
    public Result refuseRemote(@RequestBody SocketVo socketVo) {

        if(socketVo.getoId() ==null) {
            return new Result(false, "oId不能为空","-1", "");
        }
        logger.info("远程拒绝"+ JSON.toJSONString(socketVo));
        RemoteUser remoteUser = remoteUserService.getByToUser(socketVo.getoId());

        if(remoteUser==null) return new Result(false, "连接已关闭","-1", "");

        SocketBean socketBean = new SocketBean();
        socketBean.setEvent(4);
        socketBean.setToWbUserId(remoteUser.getToWbUserId());
        Map<String, Object> param = new HashMap<>();
        param.put("fromSystem", "remote");
        param.put("userIds", new String[]{remoteUser.getCreatorWbUserId()});
        param.put("msg", socketBean);

        String post = HttpClientUtils.post("https://dev.kdweibo.cn/xtinterface/extSys/sendNotify", JSON.toJSONString(param));
        logger.info("远程拒绝"+ post);
        remoteUserService.delete(remoteUser.getId());

        return new Result(true, "","", socketBean);

    }

    @ApiOperation("心跳检测")
    @PostMapping("/remoteHeartbeat.json")
    public Result remoteHeartbeat(@RequestBody SocketVo socketVo) {

        if(socketVo.getoId() ==null) {
            return new Result(false, "oId不能为空","-1", "");
        }

        RemoteUser remoteUser = remoteUserService.getByCreateUser(socketVo.getoId());
//        long l = (remoteUser.getCreateRefreshTime().getTime() - remoteUser.getToRefreshTime().getTime()) / 1000;
        if(remoteUser ==null) {
            remoteUser = remoteUserService.getByToUser(socketVo.getoId());
            if(remoteUser==null) return new Result(false, "连接已关闭","-1", "");
            remoteUser.setToRefreshTime(new Date());
        }else{
            remoteUser.setCreateRefreshTime(new Date());
        }
        remoteUserService.update(remoteUser.getId(),remoteUser);
        return new Result(true, "","", "");

    }


//    @ApiOperation("心跳检测")
//    @GetMapping("/task.json")
//    public void sysTask() {
//
//        long nowTime = System.currentTimeMillis();
//        RemoteUserVo remoteUserVo = new RemoteUserVo();
//        remoteUserVo.setPageNum(1);
//        remoteUserVo.setPageSize(1);
//
//        PageBean<RemoteUser> remoteUserPageBean = remoteUserService.pageQuery(remoteUserVo);
//
//        List<RemoteUser> list = remoteUserPageBean.getList();
//        pushShutRemote(nowTime, list);
//        for(int i=2;i<=remoteUserPageBean.getPages();i++) {
//            remoteUserVo.setPageNum(i);
//            remoteUserPageBean = remoteUserService.pageQuery(remoteUserVo);
//            list = remoteUserPageBean.getList();
//            pushShutRemote(nowTime, list);
//        }
//
//    }
//
//    private void pushShutRemote(long nowTime, List<RemoteUser> list) {
//        for (RemoteUser remoteUser : list) {
//            //超过30秒没有刷新时间则推送关闭远程的socket
//            if(nowTime-remoteUser.getCreateRefreshTime().getTime()>30) {
//                SocketBean socketBean = new SocketBean();
//                socketBean.setEvent(3);
////
//                Map<String, Object> param = new HashMap<>();
//                param.put("fromSystem", "remote");
//                param.put("userIds", new String[]{remoteUser.getCreatorWbUserId(), remoteUser.getToWbUserId()});
//                param.put("msg", socketBean);
//                remoteUserService.delete(remoteUser.getId());
////                String post = HttpClientUtils.post("https://dev.kdweibo.cn/xtinterface/extSys/sendNotify", JSON.toJSONString(param));
////                logger.info("超时推送关闭远程的socket："+ JSON.toJSONString(param));
//            }
//        }
//    }

}
